﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Globalization;
using System.Reflection;
using System.Drawing;
namespace ShapeManager
{
    
    using DrawList = List<DrawObject>;

    /// <summary> 形状列表，统一存储并管理形状 </summary>
    [Serializable]
    public class ShapeList : ISerializable
    {
        #region 字段 | 属性
        private DrawList shapeList;
        private const string entryCount = "Count";
        private const string entryType = "Type";
        public int Count { get => shapeList.Count; }
        /// <summary> 索引器 </summary> 
        public DrawObject this[int index]
        {
            get
            {
                if (index < 0 || index >= shapeList.Count) return null;
                return shapeList[index];
            }
        }
        /// <summary> 返回一个可枚举的DrawObject集合，支持迭代 </summary>
        public IEnumerable<DrawObject> Selection
        {
            get
            {
                foreach (DrawObject obj in shapeList)
                {
                    if (obj.IsSelected)
                    {
                        yield return obj;   //延迟执行
                    }
                }
            }
        }
        /// <summary> 选中个数 </summary>
        public int SelectionCount
        {
            get
            {
                int count = 0;
                foreach (DrawObject obj in Selection)
                    count++;
                return count;
            }
        }
        #endregion

        #region 构造函数
        public ShapeList()
        {
            shapeList = new DrawList();
        }
        /// <summary> 序列化支持 </summary>
        protected ShapeList(SerializationInfo info, StreamingContext context)
        {
            shapeList = new DrawList();
            int n = info.GetInt32(entryCount);
            string typeName;
            DrawObject drawObject;
            for (int i = 0; i < n; i++)
            {
                typeName = info.GetString($"{CultureInfo.InvariantCulture},{entryType}{i}");
                drawObject = (DrawObject)Assembly.GetExecutingAssembly().CreateInstance(typeName);
                drawObject.LoadFromStream(info, i);
                shapeList.Add(drawObject);
            }

        }
        #endregion

        #region 增删改查...
        /// <summary> 添加对象：插入到 Z 顺序的顶部。 </summary>
        public void Add(DrawObject obj)
        {
            shapeList.Insert(0, obj);
        }
        /// <summary> 插入指定索引中的对象为输入对象  （用于撤销操作） </summary>
        public void Insert(int index, DrawObject obj)
        {
            if (index >= 0 && index <= shapeList.Count)
            {
                shapeList.Insert(index, obj);
            }
        }
        /// <summary> 替换指定索引中的对象为输入对象  （用于撤销操作） </summary>
        public void Replace(int index, DrawObject obj)
        {
            if (index >= 0 && index < shapeList.Count)
            {
                shapeList.RemoveAt(index);
                shapeList.Insert(index, obj);
            }
        }
        /// <summary> 移除指定索引对象（用于撤销操作） </summary>
        public void RemoveAt(int index)
        {
            if (index > shapeList.Count || index < 0) return;
            shapeList.RemoveAt(index);
        }
        /// <summary> 清除集合 </summary>
        public bool Clear()
        {
            bool result = (shapeList.Count > 0);
            shapeList.Clear();
            return result;
        }

        #endregion

        #region 选择、选中
        /// <summary> 删除最后添加的对象 </summary>
        public void DeleteLastAddedObject()
        {
            if (shapeList.Count > 0)
            {
                shapeList.RemoveAt(0);
            }
        }
        /// <summary> 取消全选 </summary>
        public void UnselectAll()
        {
            foreach (DrawObject obj in shapeList)
                obj.IsSelected = false;
        }
        /// <summary> 选择所有 </summary>
        public void SelectAll()
        {
            foreach (DrawObject obj in shapeList)
                obj.IsSelected = true;
        }
        /// <summary> 删除选中(区域) </summary>
        public bool DeleteSelection()
        {
            bool result = false;
            int count = shapeList.Count;
            for (int i = count - 1; i >= 0; i--)
            {
                if ((shapeList[i]).IsSelected)
                {
                    shapeList.RemoveAt(i);
                    result = true;
                }
            }
            return result;
        }
        /// <summary> 选中区域</summary>
        public void SelectInRectangle(RectangleF rectangle)
        {
            UnselectAll();
            foreach (DrawObject obj in shapeList)
            {
                if (obj.IntersectsWith(rectangle))
                    obj.IsSelected = true;
            }
        }
        #endregion

        /// <summary> 绘制形状和矩形 </summary>
        public void Draw(Graphics graphics)
        {
            int count = shapeList.Count;
            DrawObject obj;
            // 添加方式是插入，所以按逆序列出列表，使第一个对象位于 Z 序列的最顶部。
            for (int i = count - 1; i >= 0; i--)
            {
                obj = shapeList[i];
                obj.Draw(graphics);
                if (obj.IsSelected == true)
                    obj.DrawHandles(graphics);
            }
        }

        /// <summary>
        /// 序列化时获取对象数据
        /// </summary>
        [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            
        }
    }
}
